import sys
import time
from PyQt6.QtCore import pyqtSignal, QThread
from PyQt6.QtGui import QIcon
from PyQt6.QtWidgets import QApplication, QWidget, QVBoxLayout, QProgressBar, QPushButton

from utils.index import resource_path


class ProgressThread(QThread):
    # 定义一个信号，用于发送进度值
    progress_updated = pyqtSignal(int)
    stop_signal = pyqtSignal()

    def __init__(self, start_value):
        super().__init__()
        self.start_value = start_value
        self._is_running = True
        self.stop_signal.connect(self.stop)

    def run(self):
        for i in range(self.start_value, 101):
            if not self._is_running:
                break
            time.sleep(0.4)
            # 发送进度值
            self.progress_updated.emit(i)

    def stop(self):
        self._is_running = False


# callback回调函数，当进度条到达100时执行
class Window(QWidget):
    def __init__(self, callback=None):
        super().__init__()
        self.init_widget()
        self.init_style()
        self.value = 0
        self.thread = None
        self.callback = callback

    def init_widget(self):
        self.progress_bar = QProgressBar(self)
        self.progress_bar.setRange(0, 100)
        self.progress_bar.setValue(0)
        layout = QVBoxLayout()
        layout.addWidget(self.progress_bar)
        self.setLayout(layout)
        self.resize(500, 100)  # 设置窗口大小
        # self.start_button = QPushButton('停止', self)
        # layout.addWidget(self.start_button)

    def init_style(self):
        # 设置进度条的样式表
        self.progress_bar.setStyleSheet("""
            QProgressBar {
                background-color: #E0E0E0;
                text-align: right;
                border: none;
            }
            QProgressBar::chunk {
                background-color: rgb(131, 191, 10);
                width: 20px;
                margin: 0.5px;
            }
        """)
        # 设置窗口图标和标题
        self.setWindowTitle("SeismicPlot-运行中...")
        self.setWindowIcon(QIcon(resource_path('static/image/favicon.ico')))

    def start_progress(self, value):
        # 停止正在运行的旧线程
        if self.thread and self.thread.isRunning():
            self.thread.stop_signal.emit()
            self.thread.wait()

        if value > self.value:
            self.value = value
        if self.value >= 100:
            self.close()
            return
        # 创建并启动新线程
        self.thread = ProgressThread(self.value)
        self.thread.progress_updated.connect(self.update_progress)
        self.thread.start()

    def update_progress(self, value):
        self.progress_bar.setValue(value)
        if value == 100:
            self.close()
            if self.callback:
                self.callback()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec())
